import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:rongcloud_im_plugin/rongcloud_im_plugin.dart';

import '../im/util/user_info_datesource.dart';
import 'package:provider/provider.dart';
import 'package:qaun_ni_dev/provider/rongImProvider.dart';

class ContactsPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {return new _ContactsPageState();}
}

class _ContactsPageState extends State<ContactsPage> {
  @override
  void initState() {
    super.initState();
    getConversionUserId();
  }

  getConversionUserId () async {
    Provider.of<RongImProvider>(context,listen: false).getConversionUserIdList();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("联系人列表"),
      ),
      body: Consumer<RongImProvider>(
        builder: (context,data,_) {
          if(data.conversionIdList.length > 0 ) {
            return ListView(
              children: <Widget>[
                ConversionListWidget(data.conversionIdList)
              ],
            );
          } else {
            return Center(
              child: Text('数据加载中'),
            );
          }
        },
      )
    );
  }
}

class ConversionListWidget extends StatelessWidget {
  List userIdList = [];
  ConversionListWidget(this.userIdList);

  void _onTapUser(context,BaseInfo user) {
    Map arg = {"coversationType":RCConversationType.Private,"targetId":user.id};
    Navigator.pushNamed(context, "/conversation",arguments: arg);
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 520,
      child: ListView.builder(
        itemCount: userIdList.length,
          itemBuilder: (context,index) {
            return _itemUserInfoWidget(context,index);
          }
      ),
    );
  }

  _itemUserInfoWidget(context,index) {
    var userInfoId = userIdList[index];
    BaseInfo userInfoData = UserInfoDataSource.getUserInfo(userInfoId);
    if(userInfoData !=null) {
      return Container(
        height: 50.0,
        color: Colors.white,
        child: InkWell(
          onTap: () {
            _onTapUser(context, userInfoData);
          },
          child: new ListTile(
            title: new Text(userInfoData.name),
            leading: Container(
              width: 36,
              height: 36,
              child: ClipRRect(
                borderRadius: BorderRadius.circular(5),
                child: CachedNetworkImage(
                  fit: BoxFit.fill,
                  imageUrl: userInfoData.portraitUrl,
                ),
              ),
            ),
          ),
        ),
      );
    } else {
      return ListTile(
        title: Text('数据等待中'),
      );
    }
  }
}

